package com.demo.arch.datapulsedemo.v3_reliable.controller;

import com.demo.arch.datapulsedemo.common.TaskResult;
import com.demo.arch.datapulsedemo.v2_pipeline.core.PipelineContext;
import com.demo.arch.datapulsedemo.v3_reliable.core.ContextStorage;
import com.demo.arch.datapulsedemo.v3_reliable.core.ReliablePipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * V3版本控制器（可靠Pipeline）
 * 
 * @author DataPulse Team
 */
@Slf4j
@RestController
@RequestMapping("/v3")
public class ReliableTaskController {

  @Autowired
  private ReliablePipeline pipeline;

  @Autowired
  private ContextStorage contextStorage;

  /**
   * 执行报表任务
   * 
   * 测试URL:
   * - 日报: http://localhost:8080/v3/report?type=日报
   * - 周报: http://localhost:8080/v3/report?type=周报
   * - 月报: http://localhost:8080/v3/report?type=月报
   */
  @GetMapping("/report")
  public TaskResult generateReport(@RequestParam(defaultValue = "日报") String type) {
    log.info("=== 收到V3 ReliablePipeline报表生成请求 ===");
    log.info("请求参数 - 报表类型: {}", type);

    TaskResult result = pipeline.execute(type);

    log.info("=== V3 ReliablePipeline任务执行结果: {} ===", result.isSuccess() ? "成功" : "失败");
    return result;
  }

  /**
   * 从断点恢复任务
   * 
   * 测试URL:
   * - http://localhost:8080/v3/task/recover/{taskId}
   */
  @PostMapping("/task/recover/{taskId}")
  public TaskResult recoverTask(@PathVariable String taskId) {
    log.info("=== 收到任务恢复请求: {} ===", taskId);

    TaskResult result = pipeline.recover(taskId);

    log.info("=== 任务恢复结果: {} ===", result.isSuccess() ? "成功" : "失败");
    return result;
  }

  /**
   * 查询任务状态
   * 
   * 测试URL:
   * - http://localhost:8080/v3/task/status/{taskId}
   */
  @GetMapping("/task/status/{taskId}")
  public Map<String, Object> getTaskStatus(@PathVariable String taskId) {
    log.info("=== 查询任务状态: {} ===", taskId);

    PipelineContext context = contextStorage.load(taskId);

    if (context == null) {
      Map<String, Object> result = new HashMap<>();
      result.put("exists", false);
      result.put("message", "任务不存在");
      return result;
    }

    Map<String, Object> result = new HashMap<>();
    result.put("exists", true);
    result.put("taskId", context.getTaskId());
    result.put("reportType", context.getReportType());
    result.put("currentStep", context.getCurrentStep());
    result.put("hasOrderData", context.getOrderData() != null);
    result.put("hasExcelFile", context.getExcelFilePath() != null);
    result.put("hasRecipients", context.getRecipients() != null);

    if (context.getSuccessEmails() != null) {
      result.put("successEmails", context.getSuccessEmails());
    }

    if (context.getEmailSuccessCount() != null) {
      result.put("emailSuccessCount", context.getEmailSuccessCount());
    }

    if (context.getEmailFailCount() != null) {
      result.put("emailFailCount", context.getEmailFailCount());
    }

    if (context.getErrorMessage() != null) {
      result.put("errorMessage", context.getErrorMessage());
    }

    return result;
  }

  /**
   * 查询失败任务
   * 
   * 测试URL:
   * - http://localhost:8080/v3/task/failed
   */
  @GetMapping("/task/failed")
  public List<String> getFailedTasks() {
    log.info("=== 查询失败任务 ===");

    List<String> failedTasks = contextStorage.findFailedTasks();

    log.info("=== 发现{}个失败任务 ===", failedTasks.size());
    return failedTasks;
  }

  /**
   * 健康检查接口
   */
  @GetMapping("/health")
  public TaskResult health() {
    return TaskResult.success("V3 ReliablePipeline服务正常运行");
  }
}